package com.pink.utils;

import com.pink.entity.config.Constants;
import com.pink.entity.enums.ResponseCodeEnum;
import com.pink.exception.BusinessException;
import org.springframework.stereotype.Component;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;


@Component
public class StringTool {

    public static boolean isEmpty(String str) {
        if(null == str || "".equals(str) || "null".equals(str) || "\u0000".equals(str)) {
            return true;
        } else if("".equals(str.trim())){
            return true;
        }
        return false;
    }
    //生成6个随机数字100000-999999
    public static final String generateRandomNumber() {
        return String.valueOf((int)(Math.random()*999999+100000));
    }

    //MD5加密字符串
    public static final String encodeByMD5(String originstring) {
        return MD5ExampleUtils.encodeByMD5(originstring);
    }

    // MD5校验
    public static final boolean checkByMD5(String originstring, String targetstring) {
        return MD5ExampleUtils.checkByMD5(originstring, targetstring);
    }

    public static String getRandomString(Integer length) {
        return RandomStringUtil.getRandomString(length);
    }

    public static boolean pathIsOK(String path) {

        if(StringTool.isEmpty(path)){
            return true;
        }
        if(path.contains("../") || path.contains("..\\")){
            return false;
        }
        return true;
    }

    public static String getFileSuffix(String fileName) {
        //获取文件名的扩展名
        if (fileName != null && fileName.indexOf(".") != -1) {
            return fileName.substring(fileName.lastIndexOf("."));
        }
        return null;
    }

    public static String getToken(HttpServletRequest request, String type) {
        // 从请求头中获取token Authorization:Bearer token
        String token = request.getHeader(Constants.TOKEN_HEADER);
        if (token == null) {
            // 获取Cookie中的token
            Cookie[] cookies = request.getCookies();
            if (cookies != null) {
                for (Cookie cookie : cookies) {
                    if(type.equals("web")){
                        if (Constants.TOKEN_WEB.equals(cookie.getName())) {
                            token = cookie.getValue();
                        }
                    }else{
                        if (Constants.TOKEN_ADMIN.equals(cookie.getName())) {
                            token = cookie.getValue();
                        }
                    }
                }
            }
        }else{
            if(token !=null && token.startsWith("Bearer ")){
                // 去掉Bearer
                token = token.substring(7);
            }else{
                throw new BusinessException(ResponseCodeEnum.CODE_401.getCode(), ResponseCodeEnum.CODE_401.getMessage());
            }
        }
        return token;
    }
}
